const express = require('express');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const { testConnection } = require('./config/db');
const responseMiddleware = require('./middleware/response');

// 导入路由
const authRoutes = require('./routes/auth');
const dashboardRoutes = require('./routes/dashboard');
const userRoutes = require('./routes/users');
const productRoutes = require('./routes/products');
const orderRoutes = require('./routes/orders');
const categoryRoutes = require('./routes/categories');
const uploadRoutes = require('./routes/upload');
const publicRoutes = require('./routes/public');
const systemRoutes = require('./routes/system');
const wechatRoutes = require('./routes/wechat');
const addressRoutes = require('./routes/addresses');
const miniappRoutes = require('./routes/miniapp');
const miniappImagesRoutes = require('./routes/miniappImages');
const cooperationApplicationsRoutes = require('./routes/cooperationApplications');

const app = express();
const PORT = process.env.PORT || 3129;

// 中间件配置
app.use(cors());

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 响应格式中间件
app.use(responseMiddleware);

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/dashboard', dashboardRoutes);
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/public', publicRoutes);
app.use('/api/system', systemRoutes);
app.use('/api/wechat', wechatRoutes);
app.use('/api/addresses', addressRoutes);
app.use('/api/miniapp', miniappRoutes);
app.use('/api/miniapp-images', miniappImagesRoutes);
app.use('/api/cooperation-applications', cooperationApplicationsRoutes);

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.json({
    status: 'ok',
    message: '珠宝系统API服务运行正常',
    timestamp: new Date().toISOString()
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在',
    path: req.originalUrl
  });
});

// 全局错误处理中间件
app.use((err, req, res, _next) => {
  console.error('服务器错误:', err);
  
  // 数据库连接错误
  if (err.code === 'ECONNREFUSED') {
    return res.status(500).json({
      success: false,
      message: '数据库连接失败',
      error: process.env.NODE_ENV === 'development' ? err.message : '内部服务器错误'
    });
  }
  
  // JWT错误
  if (err.name === 'JsonWebTokenError') {
    return res.status(401).json({
      success: false,
      message: '无效的访问令牌'
    });
  }
  
  if (err.name === 'TokenExpiredError') {
    return res.status(401).json({
      success: false,
      message: '访问令牌已过期'
    });
  }
  
  // 默认错误处理
  res.status(err.status || 500).json({
    success: false,
    message: err.message || '内部服务器错误',
    error: process.env.NODE_ENV === 'development' ? err.stack : '内部服务器错误'
  });
});

// 启动服务器
async function startServer() {
  try {
    // 测试数据库连接
    const dbConnected = await testConnection();
    if (!dbConnected) {
      console.error('❌ 数据库连接失败，服务器启动中止');
      process.exit(1);
    }
    
    app.listen(PORT, () => {
      console.log(`🚀 珠宝系统API服务器启动成功`);
      console.log(`📍 服务地址: http://localhost:${PORT}`);
      console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/api/health`);
    });
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('🔄 收到SIGTERM信号，正在优雅关闭服务器...');
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('🔄 收到SIGINT信号，正在优雅关闭服务器...');
  process.exit(0);
});

startServer();
